<?php
/**
 * 有赞店铺的授权信息管理
 * Author: lyun
 * Date: 2018/9/28
 * Created by Panxsoft.
 */


namespace App\Http\Controllers\Youzan;

use App\Http\Controllers\ApiController;
use App\Models\Customer\Customer;
use App\Models\Youzan\YouzanAuthorizer;
use App\Services\Utils\Guard;
use App\Services\Utils\SimpleQrCode;
use Illuminate\Http\Request;

class YouzanShopController extends ApiController
{

    /**
     *  返回客户/店铺有赞授权的店铺信息
     *
     * @return array|\Illuminate\Http\Response
     * @throws \Exception
     */
    public function show()
    {
        $customer_or_store = $this->checkIsCustomerOrStore();

        $youzan_authorizer_id = $customer_or_store->youzan_authorizer_id;
            $this->checkIsTrue($youzan_authorizer_id, trans('admin.youzan-shop'));

        /** @var YouzanAuthorizer $youzan_authorizer_info */
        $youzan_authorizer_info = YouzanAuthorizer::find($youzan_authorizer_id);
            $this->checkIsTrue($youzan_authorizer_info, trans('admin.youzan-shop'));

        $youzan_shop_url = $youzan_authorizer_info->url ?? '店铺信息错误';
        $qr_code = 'data:image/png;base64,'.base64_encode(SimpleQrCode::toImage($youzan_shop_url));

        return $this->response(compact('youzan_authorizer_info', 'qr_code'));
    }

    /**
     * @return \App\Models\Store\Store|Customer|null
     * @throws \Exception
     */
    private function checkIsCustomerOrStore()
    {
        /** @var Customer $customer */
        $customer = Guard::customer();

        if ($customer) {
            $this->checkCustomer();
        }

        $customer_or_store = $customer ?:Guard::store();

        return $customer_or_store;
    }
}
